<?php

use \GatewayWorker\Lib\Gateway;

include 'controllers\Chat.php';

class Events
{
	// 当有客户端连接时，将client_id返回，让mvc框架判断当前uid并执行绑定
	public static function onConnect($client_id)
	{
		Gateway::sendToClient($client_id, json_encode(array(
			'type'      => 'init',
			'client_id' => $client_id
		)));
	}

	/*
	 * GatewayWorker不做任何业务逻辑，onMessage留空即可
	 * message
	 *      =>  type
	 *      =>  user1
	 *      =>  user2
	 *      =>  message
	 */
	public static function onMessage($client_id, $message)
	{
		//返回的数据
		$returnData = array();
		//转换接受的数据格式
		$messageData = json_decode($message, true);

		//var_dump($messageData);

		if (isset($messageData['type'])) {
			$returnData['type'] = $messageData['type'];
		}

//		Gateway::sendToAll(json_encode(array('say'=>'hello world')));
		// 根据类型执行不同的业务

		switch($messageData['type'])
		{
			// 客户端回应服务端的心跳
			case 'pong':
				return 0;

			case 'login':
//				$res = new Chat();
				$user1 = $messageData['user1'];
				Gateway::bindUid($client_id, $user1);
				return 0;

			// 客户端发言 message: {type:say, to_client_id:xx, content:xx}
			case 'say':
				$res = new Chat();
				$res->callSay($messageData);
				if (Gateway::isUidOnline($messageData['userReceived'])) {
					$messageData['date'] = date('Y-m-d H:i:s');
					Gateway::sendToUid($messageData['userReceived'], json_encode($messageData));
				}
				return 0;
			case 'click':  //如果用户已经点击了， 将发送表中的数据转移到聊天信息表
				$res = new Chat();
				$res->callViewed($messageData);
				return 0;

			/**
			 * 接收到获取聊天列表
			 * type     getChatList
			 * restype  resChatList
			 */
			case 'getChatList':
				$chat = new Chat();
				if (!empty($messageData['userid'])) {
					$res = $chat->callGetChatList(array('userid' => $messageData['userid']));
					$response = array(
						'type' => 'resChatList',
						'data' => $res,
					);
					Gateway::sendToClient($client_id, json_encode($response));
				}
				break;

			/**
			 * 接收到获取聊天内容
			 * type     getChatList
			 * restype  resChatList
			 */
			case 'getChatInfo':
				$chat = new Chat();
				if (!empty($messageData['userid']) && !empty($messageData['userid2'])) {
					$res = $chat->callGetChatInfo($messageData);
					$response = array(
						'type' => 'resChatInfo',
						'data' => $res,
					);
					Gateway::sendToClient($client_id, json_encode($response));
				}
				break;

		}
		return 0;
	}

}
